package cn.xiaobai.utils;

import java.util.LinkedHashMap;

/**
 * @author yangdaji
 * @date 2022/6/27
 */
public class YamlUtils {

    /**
     * 获取yml配置属性
     *
     * @param sourceMap
     * @param key
     * @return
     */
    public static String getYmlProperty(LinkedHashMap<String, Object> sourceMap, String key) {
        String[] keys = key.split("[.]");
        LinkedHashMap<String, Object> cloneMap = (LinkedHashMap) sourceMap.clone();
        Object resultValue = null;
        //遍历替换map中的key,从而通过目标key获取到值
        int length = keys.length;
        for (int i = 0; i < length; i++) {
            //获取到的下一层也是map结构
            Object value = cloneMap.get(keys[i]);
            //当目标输入不是一个
            if (i < length - 1) {
                cloneMap = (LinkedHashMap<String, Object>) value;
            } else if (value == null) {
                throw new RuntimeException("key is not exists!");
            } else {
                resultValue = value;
            }
        }
        return resultValue.toString();
    }
}
